<template>
  <div class="debug-main">
    <div class="cmd-window">
      <div class="cmd-header">
        <span>调试控制台</span>
        <el-icon class="clear-btn" @click="clearLogs">
          <Delete />
        </el-icon>
      </div>
      <div class="cmd-content" ref="cmdContent">
        <div v-for="(log, index) in cmdLogs" :key="index" :class="['log-item', log.type]">
          <span v-html="log.content"></span>
        </div>
      </div>
    </div>
    <div class="function-area">
      <el-form label-width="120px">
        <h3>WebSocket 操作</h3>
        <el-form-item label="连接状态">
          <el-tag :type="wsStatus ? 'success' : 'danger'">
            {{ wsStatus ? '已连接' : '已断开' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="选择网关">
          <el-select v-model="selectedGatewayId" placeholder="请选择网关" style="width: 200px;" @change="handleGatewayChange">
            <el-option
              v-for="gateway in gatewayList"
              :key="gateway.id"
              :label="`${gateway.name} (${gateway.ip})`"
              :value="gateway.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="查询网关">
          <el-button type="primary" @click="handleQueryGateway" :disabled="!selectedGatewayId">查询网关</el-button>
        </el-form-item>
      </el-form>

      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <h3>设备ID操作</h3>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input-number 
            v-model="formData.deviceId" 
            :min="1"
            :max="999999"
            placeholder="请输入设备ID"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleDelete" :disabled="!selectedGatewayId">删除设备</el-button>
          <el-button type="success" @click="handleQueryAll" :disabled="!selectedGatewayId">查询所有设备</el-button>
        </el-form-item>
      </el-form>

      <el-form :model="addDeviceData" :rules="addDeviceRules" ref="addDeviceFormRef" label-width="120px">
        <h3>添加设备</h3>
        <el-form-item label="设备ID" prop="id">
          <el-input-number 
            v-model="addDeviceData.id" 
            :min="1"
            placeholder="请输入设备ID"
          />
        </el-form-item>
        <el-form-item label="设备ESN" prop="esn">
          <el-input 
            v-model="addDeviceData.esn" 
            placeholder="请输入设备ESN (例如: FF0100001111)"
            maxlength="12"
            @input="addDeviceData.esn = addDeviceData.esn.toUpperCase()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddDevice" :disabled="!selectedGatewayId">添加设备</el-button>
        </el-form-item>
      </el-form>

      <el-form :model="atCommandData" :rules="atCommandRules" ref="atCommandFormRef" label-width="120px" class="at-command-form">
        <h3>AT 命令操作</h3>
        <el-form-item label="设备ID" prop="id">
          <el-input-number v-model="atCommandData.id" :min="1" :max="99" />
        </el-form-item>

        <!-- 8.2 版本号 -->
        <el-form-item label="版本号">
          <el-button type="primary" @click="handleQueryVersion" :disabled="!selectedGatewayId">查询版本号</el-button>
        </el-form-item>

        <!-- 8.3 重启设备 -->
        <el-form-item label="重启设备">
          <el-button type="warning" @click="handleReboot" :disabled="!selectedGatewayId">重启设备</el-button>
        </el-form-item>

        <!-- 8.4 电路增益 -->
        <el-form-item label="电路增益">
          <el-input-number v-model="atCommandData.gain" :min="1" :max="700" :step="1" :precision="0" placeholder="增益值(1~700)" style="width: 120px;" />
          <el-button type="warning" @click="handleSetGain" :disabled="!selectedGatewayId">设置电路增益</el-button>
          <el-button type="primary" @click="handleQueryGain" :disabled="!selectedGatewayId">查询电路增益</el-button>
        </el-form-item>

        <!-- 8.5 设备类型 -->
        <el-form-item label="设备类型">
          <el-button type="primary" @click="handleQueryDType" :disabled="!selectedGatewayId">查询设备类型</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, reactive, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { gatewayStore } from '../../store/gateway';
import { storeToRefs } from 'pinia';
import { WebsocketIo } from '../../utils/websocket';

defineOptions({
  name: "Debug"
});

const cmdLogs = ref<{ type: string, content: string }[]>([]);
const cmdContent = ref<HTMLElement | null>(null);

const gateway_store = gatewayStore();
const { gatewayList } = storeToRefs(gateway_store);
const selectedGatewayId = ref<number | null>(null);

const ws = WebsocketIo.getInstance;
const wsStatus = ref(false);

onMounted(async () => {
  await gateway_store.fetchGatewayList();
  if (gatewayList.value.length > 0) {
    selectedGatewayId.value = gatewayList.value[0].id;
    handleGatewayChange(selectedGatewayId.value);
  }
});

onUnmounted(() => {
  ws.removeMessageHandler(handleWsMessage, 'gateway_result');
});

const addLog = (content: any, type = 'info') => {
  const time = new Date().toLocaleTimeString();
  let formattedContent = '';

  if (typeof content === 'object') {
    formattedContent = JSON.stringify(content, null, 2);
  } else {
    formattedContent = content;
  }

  cmdLogs.value.push({ type, content: `<span class="log-time">[${time}]</span> ${formattedContent}` });
  nextTick(() => {
    if (cmdContent.value) {
      cmdContent.value.scrollTop = cmdContent.value.scrollHeight;
    }
  });
};

const clearLogs = () => {
  cmdLogs.value = [];
};

const handleGatewayChange = (gatewayId: number) => {
  const gateway = gatewayList.value.find(g => g.id === gatewayId);
  if (gateway) {
    const url = `ws://${gateway.ip}:8081`; // 假设端口是8081
    ws.onOpen = () => {
      wsStatus.value = true;
      addLog(`与网关 ${gateway.name} (${gateway.ip}) 连接成功`, 'success');
    };
    ws.onClose = () => {
      wsStatus.value = false;
      addLog(`与网关 ${gateway.name} (${gateway.ip}) 连接断开`, 'error');
    };
    ws.onError = (err) => {
      wsStatus.value = false;
      addLog(`连接错误: ${err}`, 'error');
    };
    ws.connectWebsocket(url);
    ws.addMessageHandler(handleWsMessage, 'gateway_result');
  } else {
    // 如果找不到网关，则断开连接
    if(ws.websocketIsNormal()){
      // ws.disconnect(); // WebsocketIo 没有 disconnect 方法，但可以关闭
    }
  }
};

const handleWsMessage = (data: any) => {
  console.log('收到WebSocket消息:', data);
  
  // 格式化显示结果
  let displayResult = '';
  let logType = 'info';
  
  try {
    if (data.action === 'gateway_result') {
      const { type, result, data: responseData } = data;
      
      if (result === 'success') {
        logType = 'success';
        switch (type) {
          case 'queryGateway':
            displayResult = `网关查询成功: ${JSON.stringify(responseData, null, 2)}`;
            break;
          case 'queryAll':
            const deviceCount = Array.isArray(responseData) ? responseData.length : 0;
            displayResult = `查询所有设备成功，共找到 ${deviceCount} 个设备:\n${JSON.stringify(responseData, null, 2)}`;
            break;
          case 'add':
            displayResult = `设备添加成功: ID=${responseData?.id || 'N/A'}, ESN=${responseData?.esn || 'N/A'}`;
            break;
          case 'delete':
            displayResult = `设备删除成功: ID=${responseData?.id || 'N/A'}`;
            break;
          case 'queryVersion':
            displayResult = `版本查询成功: ${responseData?.version || '未知版本'}`;
            break;
          case 'device_reboot':
            displayResult = `设备重启成功: ID=${responseData?.id || 'N/A'}`;
            break;
          case 'queryCircuitGain':
            displayResult = `电路增益查询成功: ${responseData?.gain || '未知增益'}`;
            break;
          case 'setCircuitGain':
            displayResult = `电路增益设置成功: ID=${responseData?.id || 'N/A'}, 增益=${responseData?.gain || 'N/A'}`;
            break;
          case 'queryDeviceType':
            displayResult = `设备类型查询成功: ${responseData?.deviceType || '未知类型'}`;
            break;
          default:
            displayResult = `操作成功: ${JSON.stringify(data, null, 2)}`;
        }
      } else {
        logType = 'error';
        const errorMsg = responseData?.msg || responseData?.error || '操作失败';
        displayResult = `操作失败 [${type}]: ${errorMsg}`;
      }
    } else {
      // 非网关结果消息，直接显示
      displayResult = JSON.stringify(data, null, 2);
    }
  } catch (error) {
    logType = 'error';
    displayResult = `消息解析错误: ${JSON.stringify(data, null, 2)}`;
  }
  
  addLog(displayResult, logType);
};

const sendCommand = (payload: any) => {
  if (!ws.websocketIsNormal()) {
    ElMessage.error('WebSocket 未连接');
    return;
  }
  const gateway = gatewayList.value.find(g => g.id === selectedGatewayId.value);
  if (!gateway) {
    ElMessage.error('未选择有效的网关');
    return;
  }

  const commandToSend = {
    ...payload,
    gatewayId: gateway.ip
  };

  addLog(`发送指令: ${JSON.stringify(commandToSend, null, 2)}`, 'info');
  ws.sendMessage(JSON.stringify(commandToSend));
};

// 表单数据和规则
const formData = reactive({ deviceId: 1 });
const rules = { deviceId: [{ required: true, message: '请输入设备ID', trigger: 'blur' }] };
const formRef = ref();

const addDeviceData = reactive({ id: null, esn: '' });
const addDeviceRules = {
  id: [{ required: true, message: '请输入设备ID', trigger: 'blur' }],
  esn: [{ required: true, message: '请输入设备ESN', trigger: 'blur' }]
};
const addDeviceFormRef = ref();

const atCommandData = reactive({ id: null, gain: null });
const atCommandRules = { id: [{ required: true, message: '请输入设备ID', trigger: 'blur' }] };
const atCommandFormRef = ref();

// 操作处理函数
const handleQueryGateway = () => sendCommand({ action: 'gateway', type: 'queryGateway' });
const handleDelete = () => formRef.value.validate((valid: boolean) => valid && sendCommand({ action: 'gateway', type: 'delete', id: formData.deviceId }));
const handleQueryAll = () => sendCommand({ action: 'gateway', type: 'queryAll' });
const handleAddDevice = () => addDeviceFormRef.value.validate((valid: boolean) => valid && sendCommand({ action: 'gateway', type: 'add', ...addDeviceData }));
const handleQueryVersion = () => atCommandFormRef.value.validate((valid: boolean) => valid && sendCommand({ action: 'gateway', type: 'queryVersion', id: atCommandData.id }));
const handleReboot = () => atCommandFormRef.value.validate((valid: boolean) => valid && sendCommand({ action: 'gateway', type: 'device_reboot', id: atCommandData.id }));
const handleSetGain = () => atCommandFormRef.value.validate((valid: boolean) => valid && atCommandData.gain && sendCommand({ action: 'gateway', type: 'setCircuitGain', id: atCommandData.id, gain: atCommandData.gain }));
const handleQueryGain = () => atCommandFormRef.value.validate((valid: boolean) => valid && sendCommand({ action: 'gateway', type: 'queryCircuitGain', id: atCommandData.id }));
const handleQueryDType = () => atCommandFormRef.value.validate((valid: boolean) => valid && sendCommand({ action: 'gateway', type: 'queryDeviceType', id: atCommandData.id }));
</script>

<style scoped lang="less">
.debug-main {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.cmd-window {
  flex: 0 0 45%;
  min-width: 400px;
  max-width: 600px;
  height: 80vh;
  background: #1e1e1e;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .cmd-header {
    background: #2d2d2d;
    padding: 8px 16px;
    color: #fff;
    font-size: 14px;
    border-bottom: 1px solid #3d3d3d;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .cmd-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    color: #fff;
    font-family: 'Consolas', monospace;
    
    .log-item {
      margin-bottom: 4px;
      word-break: break-all;
      
      .log-time {
        color: #52c41a; // 绿色
        margin-right: 5px;
      }
      
      &.error {
        color: #ff4d4f;
      }
      
      &.success {
        color: #52c41a;
      }
      
      &.info {
        color: #1890ff;
      }
    }

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 8px;
      background: #232323;
    }
    &::-webkit-scrollbar-thumb {
      background: #444;
      border-radius: 6px;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: #666;
    }
    &::-webkit-scrollbar-corner {
      background: #232323;
    }
  }
}

.function-area {
  flex: 1;
  min-width: 350px;
  background: #fff;
  padding: 32px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  gap: 20px;

  h3 {
    margin-top: 0;
    margin-bottom: 15px;
    color: #333;
  }

  .el-form-item {
    margin-bottom: 10px;
  }
  
  :deep(.el-form-item__content) {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .at-command-form .el-form-item .el-input-number {
    width: 100px;
  }

  .at-command-form .el-form-item .el-select {
    width: 120px;
  }
}

.clear-btn {
  cursor: pointer;
  font-size: 20px;
  color: #ff4d4f;
  transition: color 0.2s;
  margin-left: 16px;
  &:hover {
    color: #ff7875;
  }
}
</style>
